﻿/*
 * @author: wizardc
 */

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace Dou.Resource
{
    /// <summary>
    /// 热更新数据清单文件
    /// </summary>
    public class HotFixedManifest
    {
        private const string FetchRegex = "^([a-zA-Z0-9\\.]+)\\|([0-9a-fA-F]+)\\|([0-9]+)$";
        
        /// <summary>
        /// 文件信息表
        /// key -> 文件名, value -> 文件信息
        /// </summary>
        public Dictionary<string, FileInfo> fileInfoMap = new Dictionary<string, FileInfo>();

        /// <summary>
        /// 解码
        /// </summary>
        public void Decode(string content)
        {
            var matches = Regex.Matches(content, FetchRegex, RegexOptions.Multiline);
            foreach (Match match in matches)
            {
                var fileName = match.Groups[1].Value;
                var hashCode = match.Groups[2].Value;
                var size = int.Parse(match.Groups[3].Value);
                fileInfoMap.Add(fileName, new FileInfo
                {
                    fileName = fileName,
                    hashCode = hashCode,
                    size = size
                });
            }
        }

#if UNITY_EDITOR
        
        /// <summary>
        /// 编码
        /// </summary>
        public string Encode()
        {
            var stringBuilder = new StringBuilder();
            var list = fileInfoMap.Values.ToList();
            list.Sort((a, b) => a.fileName.CompareTo(b.fileName));
            foreach (var fileInfo in list)
            {
                stringBuilder.Append(fileInfo.fileName);
                stringBuilder.Append('|');
                stringBuilder.Append(fileInfo.hashCode);
                stringBuilder.Append('|');
                stringBuilder.Append(fileInfo.size);
                stringBuilder.Append('\r');
            }
            return stringBuilder.ToString();
        }
        
#endif
        
        /// <summary>
        /// 单个文件信息
        /// </summary>
        public class FileInfo
        {
            /// <summary>
            /// 文件名
            /// </summary>
            public string fileName;

            /// <summary>
            /// 文件 MD5 码
            /// </summary>
            public string hashCode;

            /// <summary>
            /// 文件大小，单位字节
            /// </summary>
            public int size;
        }
    }
}
